package com.lute.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.BusinessUnit;
import com.lute.model.Client;
import com.lute.model.ClientAccountingPeriod;
import com.lute.model.ClientProfile;
import com.lute.model.UserEntitlement;
import com.lute.utils.ServerErrorResponse;

@Controller
public class GetCurrentAccountingPeriodServlet {
	
	@RequestMapping (value="/getCurrentAccountingPeriodId",method= RequestMethod.POST, headers = "Content-type=application/json")
	public @ResponseBody String getCurrentAccountingPeriodId(@RequestBody String dataJSON, HttpServletRequest request) throws JSONException {
		String result = "";
		String clientId;
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		System.out.println(dataJSON);
		
		try {
			jsonReq = new JSONObject(dataJSON);
			clientId = jsonReq.getString("clientId");
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		/* check if json data was not malformed */
		if((jsonReq.isNull("clientId"))) {
			jsonRes.put("result",ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		String role = (String)session.getAttribute("role");
		
		/* check  authorization */
		if(!(((role.equals("clientAdmin")) || (role.equals("approver")) || (role.equals("employee"))))) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		
		int sessionUserId = (Integer)session.getAttribute("sessionUserId");
		int id_client = Integer.parseInt(clientId);
		
		/* check if clientAdmin has privilege to client */
		ClientProfile clientProfile = null;
		if(role.equals("clientAdmin")) {
			clientProfile = UserEntitlement.checkClientAdminPrivilegeToClientProfile(sessionUserId, id_client);
			
		} else {
			clientProfile = UserEntitlement.checkEmployeePrivilegeToClient(role, sessionUserId, id_client);
		}
		
		if(clientProfile == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String currentPeriod = "";
		jsonRes.put("result", "");
		
		try {
			
			ClientAccountingPeriod clientPeriod = ClientAccountingPeriod.getClientCurrentAccountinPeriod(id_client, jsonRes);
			
			if(!(jsonRes.get("result").equals(""))) {
				result = jsonRes.toString();
				return result;
			}
			
			if(clientPeriod == null) {
				jsonRes.put("result", ServerErrorResponse.NO_CURRENT_PERIOD_AVAILABLE.toString());
				result = jsonRes.toString();
				return result;
			}
			
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			GregorianCalendar period = clientPeriod.getDate_from();
			currentPeriod = dateFormater.format(period.getTime());
			
		}catch(NullPointerException npe){
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			npe.printStackTrace();
			return result;
		}
		
		jsonRes.put("result","OK");
		jsonRes.put("from",currentPeriod);
		result = jsonRes.toString();
		return result;
	}
}
